package cn.ymz.listener;

import cn.hutool.cache.Cache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ymz.service.CallService;
import cn.ymz.service.LoginService;
import cn.ymz.service.impl.CallServiceImpl;

import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.ArrayList;
import java.util.Map;
import java.util.TimerTask;

public class ClipListener extends TimerTask {


    private static final Log log = LogFactory.get();

    CallService callService = CallServiceImpl.getInstance();

    private final Cache<String, Object> cache;


    public ClipListener(Cache<String, Object> cache) {
        this.cache = cache;
    }

    java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //获得系统剪贴板


    private String actionPerformed() {
        String string = "";
        Transferable contents = clipboard.getContents(this); //得到剪贴板内容
        if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { //判断内容是否为空,是否为字符串
            try {
                string = (String) contents.getTransferData(DataFlavor.stringFlavor); //转换内容到字符串
            } catch (Exception ex) {
                ex.printStackTrace(); //错误处理
            }
        }
        return string;
    }

    @Override
    public void run() {
        try {
            Map<String, JSONObject> userMap = LoginService.USER_MAP;
            if (userMap.size() == 0) {
                return;
            }
            String result = actionPerformed();
            // 一小时 同一个号码 只打一次 电话
            if (!StrUtil.isEmpty(result)) {
                String regex = "1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\\d|9\\d)\\d{8}";
                java.util.List<String> numberList = ReUtil.findAll(regex, result, 0, new ArrayList<>());
                if (!CollUtil.isEmpty(numberList)) {
                    for (String mobile : numberList) {
                        if (!cache.containsKey(mobile)) {
                            log.info("开始拨打，号码：" + mobile);
                            // 打电话
                            callService.call(mobile);
                            cache.put(mobile, true);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
